#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
using std::cout;
using std::cin;
using std::endl;
extern Log log;

//一个端口号只能被一个进程bind
//客户端不要绑定IP与端口, 让系统自己绑定(若绑定端口, 假设A进程的端口为8080, B进程也就是这个进程绑定了8080, B进程先启动, A进程就无法启动了)
//客户端知道服务端IP地址和端口就行
class udp_client
{
private:
    int _sockfd = 0;

public:
    udp_client(){}
    ~udp_client(){if(_sockfd > 0)close(_sockfd); }

    void Init();
    void Run();
};

void udp_client::Init()
{
    //创建套接字
    _sockfd = socket(AF_INET, SOCK_DGRAM, 0);//可能创建失败
    if(_sockfd < 0){ log(Fatal, "create socket fali "); exit(1);}
    log(Info, "create socket success %d",_sockfd);
}

void udp_client::Run()
{
    //填充服务器信息
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(8080);
    server.sin_addr.s_addr = inet_addr("127.0.0.1");

    while(1)
    {
        //发送数据
        std::string message;
        std::getline(cin, message);
        sendto(_sockfd, message.c_str(), sizeof(message), 0 , (sockaddr*)&server, sizeof(server));
        cout << "client say " << message << endl;
        if(message == "quit")break;

        //接收数据
        char inbuffer[1024];
        recvfrom(_sockfd, inbuffer, sizeof(inbuffer) , 0, NULL, NULL);
        cout << "server say: " << inbuffer << endl;

        memset(inbuffer, 0, sizeof(inbuffer));
    }

    log(Info, "client quit");
    close(_sockfd);
}



